'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import AppHeader from '@/components/ui/app-header';
import { PlusIcon } from '@heroicons/react/24/outline';
import { projectApi, taskApi, userApi } from '@/lib/api';

// 在文件顶部添加类型定义
interface Project {
  id: string;
  name: string;
  description?: string;
  status: string;
  tasks?: {
    total: number;
    completed: number;
  };
}

interface Task {
  id: string;
  title: string;
  status: string;
  projectId: string;
  projectName?: string;
}

interface DashboardData {
  projects: Project[];
  stats: {
    totalProjects: number;
    completedTasks: number;
    totalTasks: number;
    inProgressTasks: number;
  };
  tasks: Task[];
}

export default function DashboardPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // 修改状态初始化
  const [dashboardData, setDashboardData] = useState<DashboardData>({
    projects: [],
    stats: {
      totalProjects: 0,
      completedTasks: 0,
      totalTasks: 0,
      inProgressTasks: 0
    },
    tasks: []
  });
  
  // 如果未登录，重定向到登录页面
  useEffect(() => {
    if (status === 'unauthenticated') {
      router.push('/auth/login');
    }
  }, [status, router]);
  
  useEffect(() => {
    async function fetchDashboardData() {
      // 如果用户未登录或正在加载认证状态，不执行数据获取
      if (status !== 'authenticated' || !session?.user) {
        return;
      }
      
      setLoading(true);
      setError(null);
      
      try {
        console.log('开始获取仪表盘数据...');
        
        // 定义默认值，确保即使API请求失败也有基本数据显示
        let userStats = {
          stats: {
            projects: { total: 0, active: 0, completed: 0 },
            tasks: { completed: 0, inProgress: 0, pending: 0, review: 0 }
          }
        };
        
        let projectsArray = [];
        let tasks = [];
        
        // 1. 获取用户统计数据
        try {
        console.log('获取用户统计数据...');
          userStats = await userApi.getUserStats(session.user.id);
        console.log('用户统计数据获取成功:', userStats);
        } catch (userStatsError) {
          console.error('获取用户统计数据失败，使用默认值:', userStatsError);
          // 不设置全局错误，继续获取其他数据
        }
        
        // 2. 获取项目列表
        try {
        console.log('获取项目列表...');
        const projects = await projectApi.getProjects();
        console.log('项目列表获取成功:', projects);
        
        // 检查项目数据是否正确
        if (!projects) {
          console.warn('项目列表为空或未定义，使用空数组');
        }
        
        // 确保projects是数组
          projectsArray = Array.isArray(projects) ? projects : 
                              (projects && Array.isArray(projects.data)) ? projects.data : [];
        
        console.log('处理后的项目数组:', projectsArray);
        } catch (projectsError) {
          console.error('获取项目列表失败，使用空数组:', projectsError);
          // 不设置全局错误，继续获取其他数据
        }
        
        // 3. 获取任务列表
        if (projectsArray.length > 0) {
          try {
            console.log(`获取项目任务 (项目ID: ${projectsArray[0].id})...`);
            // 尝试获取第一个项目的任务
            const projectTasks = await taskApi.getTasks(projectsArray[0].id);
            console.log('项目任务获取成功:', projectTasks);
            
            // 确保tasks是数组
            tasks = Array.isArray(projectTasks) ? projectTasks : 
                    (projectTasks && Array.isArray(projectTasks.data)) ? projectTasks.data : [];
            
            console.log('处理后的任务数组:', tasks);
          } catch (taskError) {
            console.error('获取任务失败，使用空数组:', taskError);
            // 任务获取失败不影响整体加载
          }
        } else {
          console.log('没有可用项目，跳过获取任务');
        }
        
        // 计算统计数据
        const taskStats = {
          completedTasks: userStats?.stats?.tasks?.completed || 0,
          totalTasks: (userStats?.stats?.tasks?.completed || 0) + 
                      (userStats?.stats?.tasks?.inProgress || 0) + 
                      (userStats?.stats?.tasks?.pending || 0) + 
                      (userStats?.stats?.tasks?.review || 0),
          inProgressTasks: userStats?.stats?.tasks?.inProgress || 0
        };
        
        // 更新状态
        setDashboardData({
          projects: projectsArray,
          stats: {
            totalProjects: projectsArray.length,
            ...taskStats
          },
          tasks: tasks
        });
        
        console.log('仪表盘数据获取完成');
      } catch (err: any) {
        console.error('获取仪表盘数据失败:', err);
        
        // 详细的错误处理
        if (err.response) {
          console.error('错误响应数据:', err.response.data);
          console.error('错误状态码:', err.response.status);
          setError(`获取数据失败: ${err.response.data?.message || err.response.data?.error || err.message || '请稍后重试'}`);
        } else if (err.request) {
          console.error('请求发送但未收到响应');
          setError('服务器未响应，请检查网络连接');
        } else if (err.message) {
          setError(`获取数据失败: ${err.message}`);
        } else {
          setError('获取数据失败，请稍后重试');
        }
      } finally {
        setLoading(false);
      }
    }
    
    fetchDashboardData();
  }, [session, status]);

  // 如果用户未登录或正在加载认证状态，显示加载状态
  if (status === 'loading' || status === 'unauthenticated') {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 mx-auto mb-4"></div>
          <p className="text-gray-600">{status === 'unauthenticated' ? '正在重定向到登录页面...' : '加载中...'}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <AppHeader
          title="NextCollab项目管理"
          subtitle="查看并管理您的项目和任务"
          actions={(
            <Link
              href="/project/new"
              className="inline-flex items-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus:outline-none"
            >
              <PlusIcon className="-ml-0.5 mr-1.5 h-5 w-5" aria-hidden="true" />
              创建项目
            </Link>
          )}
        />

        {error && (
          <div className="mt-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative" role="alert">
            <span className="block sm:inline">{error}</span>
          </div>
        )}

        {loading ? (
          <div className="mt-6 grid grid-cols-1 gap-6 sm:grid-cols-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="bg-white overflow-hidden shadow rounded-lg p-5 animate-pulse">
                <div className="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
                <div className="h-6 bg-gray-200 rounded w-1/4"></div>
              </div>
            ))}
          </div>
        ) : (
          <div className="mt-6 grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {/* 统计卡片 */}
            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0 bg-blue-500 rounded-md p-3">
                    <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">总项目数</dt>
                      <dd>
                        <div className="text-lg font-medium text-gray-900">{dashboardData.stats.totalProjects}</div>
                      </dd>
                    </dl>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-5 py-3">
                <div className="text-sm">
                  <Link href="/project" className="font-medium text-blue-600 hover:text-blue-500">查看所有项目</Link>
                </div>
              </div>
            </div>

            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0 bg-green-500 rounded-md p-3">
                    <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">已完成任务</dt>
                      <dd>
                        <div className="text-lg font-medium text-gray-900">
                          {dashboardData.stats.completedTasks}/{dashboardData.stats.totalTasks}
                        </div>
                      </dd>
                    </dl>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-5 py-3">
                <div className="text-sm">
                  <Link href="/task" className="font-medium text-blue-600 hover:text-blue-500">查看所有任务</Link>
                </div>
              </div>
            </div>

            <div className="bg-white overflow-hidden shadow rounded-lg">
              <div className="p-5">
                <div className="flex items-center">
                  <div className="flex-shrink-0 bg-yellow-500 rounded-md p-3">
                    <svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </div>
                  <div className="ml-5 w-0 flex-1">
                    <dl>
                      <dt className="text-sm font-medium text-gray-500 truncate">进行中任务</dt>
                      <dd>
                        <div className="text-lg font-medium text-gray-900">{dashboardData.stats.inProgressTasks}</div>
                      </dd>
                    </dl>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-5 py-3">
                <div className="text-sm">
                  <Link href="/task?status=in-progress" className="font-medium text-blue-600 hover:text-blue-500">查看进行中任务</Link>
                </div>
              </div>
            </div>
          </div>
        )}

        <div className="mt-8">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-medium text-gray-900">最近的项目</h2>
            <Link href="/project" className="text-sm font-medium text-blue-600 hover:text-blue-500">
              查看全部
            </Link>
          </div>
          {loading ? (
            <div className="bg-white shadow overflow-hidden sm:rounded-md p-4">
              <div className="animate-pulse">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="mb-4 last:mb-0">
                    <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
                    <div className="h-3 bg-gray-200 rounded w-1/2 mb-4"></div>
                    <div className="h-2 bg-gray-200 rounded w-full"></div>
                  </div>
                ))}
              </div>
            </div>
          ) : dashboardData.projects.length === 0 ? (
            <div className="bg-white shadow overflow-hidden sm:rounded-md p-8 text-center">
              <p className="text-gray-500">暂无项目数据</p>
              <Link 
                href="/project/new" 
                className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
              >
                创建您的第一个项目
              </Link>
            </div>
          ) : (
            <div className="bg-white shadow overflow-hidden sm:rounded-md">
              <ul className="divide-y divide-gray-200">
                {dashboardData.projects.slice(0, 3).map((project) => {
                  // 计算完成率
                  const totalTasks = project.tasks?.total || 0;
                  const completedTasks = project.tasks?.completed || 0;
                  const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
                  
                  return (
                    <li key={project.id}>
                      <Link href={`/project/${project.id}`} className="block hover:bg-gray-50">
                        <div className="px-4 py-4 sm:px-6">
                          <div className="flex items-center justify-between">
                            <div className="truncate">
                              <div className="flex items-center">
                                <p className="text-sm font-medium text-blue-600 truncate">{project.name}</p>
                                <div className={`ml-2 flex-shrink-0 flex ${
                                  project.status === 'COMPLETED' ? 'bg-green-100' : 
                                  project.status === 'IN_PROGRESS' ? 'bg-yellow-100' : 'bg-gray-100'
                                } rounded-full`}>
                                  <p className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                                    project.status === 'COMPLETED' ? 'text-green-800' : 
                                    project.status === 'IN_PROGRESS' ? 'text-yellow-800' : 'text-gray-800'
                                  }`}>
                                    {project.status === 'COMPLETED' ? '已完成' : 
                                     project.status === 'IN_PROGRESS' ? '进行中' : '规划中'}
                                  </p>
                                </div>
                              </div>
                              <div className="mt-1 text-sm text-gray-500">
                                {project.description || '无描述'}
                              </div>
                            </div>
                            <div className="ml-4 flex-shrink-0 flex">
                              <p className="text-sm text-gray-500">
                                {completedTasks} / {totalTasks} 任务完成
                              </p>
                              <div className="ml-4 w-32 bg-gray-200 rounded-full h-2.5 dark:bg-gray-200">
                                <div 
                                  className="bg-blue-600 h-2.5 rounded-full" 
                                  style={{ width: `${completionRate}%` }}
                                ></div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          )}
        </div>

        <div className="mt-8">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-medium text-gray-900">待办任务</h2>
            <Link href="/task" className="text-sm font-medium text-blue-600 hover:text-blue-500">
              查看全部
            </Link>
          </div>
          {loading ? (
            <div className="bg-white shadow overflow-hidden sm:rounded-md p-4">
              <div className="animate-pulse">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="mb-4 last:mb-0 flex items-center">
                    <div className="h-4 w-4 bg-gray-200 rounded-full mr-3"></div>
                    <div className="h-4 bg-gray-200 rounded w-1/3"></div>
                    <div className="ml-auto h-3 bg-gray-200 rounded w-1/5"></div>
                  </div>
                ))}
              </div>
            </div>
          ) : dashboardData.tasks.length === 0 ? (
            <div className="bg-white shadow overflow-hidden sm:rounded-md p-8 text-center">
              <p className="text-gray-500">暂无待办任务</p>
              {dashboardData.projects.length > 0 && (
                <Link 
                  href={`/task/new?projectId=${dashboardData.projects[0].id}`}
                  className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
                >
                  创建新任务
                </Link>
              )}
            </div>
          ) : (
            <div className="bg-white shadow overflow-hidden sm:rounded-md">
              <ul className="divide-y divide-gray-200">
                {dashboardData.tasks.filter(task => task.status !== 'DONE').slice(0, 3).map((task) => (
                  <li key={task.id}>
                    <div className="px-4 py-4 flex items-center sm:px-6">
                      <input
                        id={`task-${task.id}`}
                        name={`task-${task.id}`}
                        type="checkbox"
                        checked={task.status === 'DONE'}
                        readOnly
                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                      <label htmlFor={`task-${task.id}`} className="ml-3 block text-sm font-medium text-gray-700">
                        {task.title}
                      </label>
                      <span className="ml-auto text-sm text-gray-500">{task.projectName || '未分配项目'}</span>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </main>
    </div>
  );
} 